import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { ProductCard, Stepper, Checkbox, SubmitBar } from "react-vant";
import {
  addCart,
  changeAllState,
  changeState,
  subCart,
} from "../../store/cart/cartSlice";
import "./style.scss";
const Cart = () => {
  const cart = useSelector((state) => state.cart.cartList);
  const dispatch = useDispatch();
  const allState = cart.every((v) => v.state);
  const allPrice = cart
    .filter((v) => v.state)
    .reduce((p, n) => {
      return p + n.count * n.price;
    }, 0);
  return (
    <div>
      {cart.map((v) => {
        return (
          <div style={{ display: "flex" }} key={v.id}>
            <div style={{ flexShrink: 0, marginTop: 10 }}>
              <Checkbox
                checked={v.state}
                onClick={() => dispatch(changeState(v))}
              ></Checkbox>
            </div>
            <div style={{ flex: 1, overflow: "hidden" }}>
              <ProductCard
                style={{ width: "100%" }}
                key={v.id}
                num={
                  <Stepper
                    min={1}
                    value={v.count}
                    onPlus={() => dispatch(addCart(v))}
                    onMinus={() => dispatch(subCart(v))}
                  ></Stepper>
                }
                price={v.price}
                desc={<div className="rv-ellipsis">{v.desc}</div>}
                title={v.title}
                thumb={v.image}
              ></ProductCard>
            </div>
          </div>
        );
      })}

      <SubmitBar price={allPrice * 100} buttonText="提交订单">
        <Checkbox
          checked={allState}
          onClick={() => dispatch(changeAllState(!allState))}
        >
          全选
        </Checkbox>
      </SubmitBar>
    </div>
  );
};

export default Cart;
